package sunyu.demo.mina;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import sunyu.toolkit.core.FileKit;
import sunyu.toolkit.core.LogKit;
import sunyu.toolkit.core.StringKit;
import sunyu.toolkit.core.TimeKit;
import sunyu.toolkit.mina.SocketClientTemplate;

import java.io.File;
import java.util.Date;

/**
 * @author 孙宇
 */
public class ProtocolSocketClient extends SocketClientTemplate {
    private static final Logger logger = LogKit.getLogger();
    File file;

    public ProtocolSocketClient(String host, int port, File file) {
        super(host, port);
        this.file = file;
    }

    @Override
    public void messageReceived(IoSession iosession, Object message) throws Exception {
        IoBuffer bbuf = (IoBuffer) message;
        byte[] byten = new byte[bbuf.limit()];
        bbuf.get(byten, bbuf.position(), bbuf.limit());
        logger.debug("客户端收到消息 {}", byten);
        String hexString = StringKit.bytes2hexString(byten);
        FileKit.appendContentAndRN(file, "[" + TimeKit.format("yyyy-MM-dd HH:mm:ss", new Date()) + "] [应答] " + hexString);
        logger.debug("客户端收到消息 {}", hexString);
    }
}
